package boss.portal.service.impl;

import boss.portal.entity.logg.UserOptLoggerEntity;
import boss.portal.repository.UserOptLoggerRepository;
import boss.portal.service.IUserOptLogService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

@Slf4j
@Service("userOptLogService")
public class UserOptLogServiceImpl implements IUserOptLogService {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchTemplate;
    @Autowired
    private UserOptLoggerRepository userOptLoggerRepository;
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    private Pageable pageable = PageRequest.of(0, 10);

    @Override
    public void createIndex() {
        elasticsearchTemplate.createIndex(UserOptLoggerEntity.class);
    }

//    @Override
//    public void createIndex() {
//        try {
//            if (this.existIndex(IUserOptLogService.USER_OPT_LOGGER)) {
//                return;
//            }
//
//            // 创建 Mapping
//            XContentBuilder mapping = XContentFactory.jsonBuilder()
//                    .startObject()
//                        .field("dynamic", true)
//                        .startObject("properties")
//                            .startObject("firmId")
//                                .field("type","keyword")
//                            .endObject()
//                            .startObject("operator")
//                                .field("type","keyword")
//                            .endObject()
//                            .startObject("optModule")
//                                .field("type","keyword")
//                            .endObject()
//                            .startObject("optType")
//                                .field("type","keyword")
//                            .endObject()
//                            .startObject("optTime")
//                                .field("type","date")
//                                .field("format","date_optional_time")
//                            .endObject()
//                            .startObject("ip")
//                                .field("type","text")
//                            .endObject()
//                            .startObject("content")
//                                .field("type","text")
//                                .field("analyzer","ik_max_word")
//                            .endObject()
//                        .endObject()
//                    .endObject();
//            // 创建索引配置信息，配置
//            Settings settings = Settings.builder()
//                    .put("index.number_of_shards", 1)
//                    .put("index.number_of_replicas", 0)
//                    .build();
//            // 新建创建索引请求对象，然后设置索引类型（ES 7.0 将不存在索引类型）和 mapping 与 index 配置
//            CreateIndexRequest request = new CreateIndexRequest(IUserOptLogService.USER_OPT_LOGGER);
//            request.settings(settings);
//            request.mapping("doc", XContentType.JSON);
//            request.mapping(mapping);
//            // RestHighLevelClient 执行创建索引
//            CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
//            // 判断是否创建成功
//            boolean isCreated = createIndexResponse.isAcknowledged();
//            log.info("是否创建成功：{}", isCreated);
//        } catch (IOException e) {
//            log.error("", e);
//        }
//
//    }

    @Override
    public void deleteIndex(String index) {
        elasticsearchTemplate.deleteIndex(index);
    }

//    @Override
//    public void deleteIndex(String index) {
//        try {
//            if (!this.existIndex(index)) {
//                return;
//            }
//
//            // 新建删除索引请求对象
//            DeleteIndexRequest request = new DeleteIndexRequest(index);
//            // 执行删除索引
//            AcknowledgedResponse acknowledgedResponse = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
//            // 判断是否删除成功
//            boolean siDeleted = acknowledgedResponse.isAcknowledged();
//            log.info("是否删除成功：{}", siDeleted);
//        } catch (IOException e) {
//            log.error("", e);
//        }
//    }

    @Override
    public boolean existIndex(String index) {
        boolean exist = false;
        try {
            GetIndexRequest indexRequest = new GetIndexRequest(index);
            return restHighLevelClient.indices().exists(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("", e);
        }
        return exist;
    }

    @Override
    public void save(UserOptLoggerEntity docBean) {
        userOptLoggerRepository.save(docBean);
    }

    @Override
    public void saveAll(List<UserOptLoggerEntity> list) {
        userOptLoggerRepository.saveAll(list);
    }

    @Override
    public Iterator<UserOptLoggerEntity> findAll() {
        return userOptLoggerRepository.findAll().iterator();
    }

    @Override
    public Page<UserOptLoggerEntity> findByContent(String content) {
        return userOptLoggerRepository.findByContent(content, pageable);
    }

    @Override
    public Page<UserOptLoggerEntity> findByFirmId(String firmId) {
        return userOptLoggerRepository.findByFirmId(firmId, pageable);
    }

    @Override
    public Page<UserOptLoggerEntity> findByOperator(String operator) {
        return userOptLoggerRepository.findByOperator(operator, pageable);
    }

    @Override
    public Page<UserOptLoggerEntity> findByOptModule(String optModule) {
        return userOptLoggerRepository.findByOptModule(optModule, pageable);
    }

    @Override
    public Page<UserOptLoggerEntity> findByOptType(String optType) {
        return userOptLoggerRepository.findByOptType(optType, pageable);
    }

    @Override
    public Page<UserOptLoggerEntity> query(String key) {
        return userOptLoggerRepository.findByContent(key, pageable);

    }

}
